<?php

namespace JsonLowCode\UI;

use JsonLowCode\Schema;
use JsonLowCode\Helps\Random;
use JsonLowCode\Traits\Events\HasOnUpdateValue;
use JsonLowCode\Traits\Props\HasValue;
use Smarty\Smarty;

/**
 * SfcLocal 本地Sfc组件
 * @method static SfcLocal make(string $view = null, array $data = []) SfcLocal 本地Sfc组件
 */
class SfcLocal extends Schema
{
    protected string $componentName = "SfcLocal";

    use HasValue;

    use HasOnUpdateValue;



    public function __construct(string $view = null, array $data = [])
    {
        parent::__construct();
        $name = $this->componentName.ucfirst($view);
//        $this->filepath("views");
        $this->filename($name);
        $view!=null && $this->view($view, $data);
    }

    /**
     * @param $filename
     * @return $this
     */
    public function filename($filename): static
    {
        return $this->prop("filename",rtrim($filename,".vue").".vue");
    }

    /**
     * @param $filepath
     * @return $this
     */
    public function filepath($filepath): static
    {
        return $this->prop("filepath",$filepath);
    }

    /**
     * @param string $view 视图路径
     * @param array $data 视图数据
     * @return $this
     */
    public function view(string $view, array $data = []): static
    {
        if (function_exists("view")){
            $viewRender = view($view, $data)->render();
        }else{
            $viewRender = $this->render($view, $data);
        }
        return $this->prop("tpl",$viewRender);
    }

    protected function render(string $view, array $data = [])
    {
        $smarty = new Smarty();
        foreach ($data as $key=>$value){
            $smarty->assign($key, $value);
        }
        return $smarty->fetch($_SERVER["DOCUMENT_ROOT"]."/../components/".$view.".php");
//        dump($_SERVER["DOCUMENT_ROOT"]."/../components/".$view.".php");die;
//        require $_SERVER["DOCUMENT_ROOT"]."/../components/".$view.".php";
//        return <<<HTML
//<template>
//    <div>$view,  {$data['test']}</div>
//</template>
//<script setup>
//
//</script>
//HTML;
    }
}
